package com.xuxin.baby.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ArrayUtils;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.tencent.liteav.demo.play.SuperPlayerConst;
import com.tencent.liteav.demo.play.SuperPlayerModel;
import com.tencent.liteav.demo.play.SuperPlayerVideoId;
import com.tencent.liteav.demo.play.SuperPlayerView;
import com.xuxin.baby.R;
import com.xuxin.baby.adapter.VideoTagAdapter;
import com.xuxin.baby.base.BaseActivity;
import com.xuxin.baby.base.BaseConstant;
import com.xuxin.baby.bean.BaseBean;
import com.xuxin.baby.bean.IsBuyBean;
import com.xuxin.baby.bean.VideoBean;
import com.xuxin.baby.bean.VideoCollectedBean;
import com.xuxin.baby.contract.CollectContract;
import com.xuxin.baby.contract.LikeContract;
import com.xuxin.baby.contract.VideoContract;
import com.xuxin.baby.database.DBControl;
import com.xuxin.baby.glide.GlideApp;
import com.xuxin.baby.network.Retrofit;
import com.xuxin.baby.presenter.CollectPresenter;
import com.xuxin.baby.presenter.LikePresenter;
import com.xuxin.baby.presenter.VideoPresenter;
import com.xuxin.baby.utils.ACache;
import com.xuxin.baby.utils.RecycleUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by xu_xin
 * Created on 2020.06.29 0020
 * 视频播放
 */
public class VideoActivity extends BaseActivity implements VideoContract.View,
        CollectContract.View, LikeContract.View, SuperPlayerView.OnSuperPlayerViewCallback {
    private final VideoContract.Presenter presenter = new VideoPresenter(this);
    private final CollectContract.Presenter presenter2 = new CollectPresenter(this);
    private final LikeContract.Presenter presenter3 = new LikePresenter(this);
    @BindView(R.id.video_player)
    SuperPlayerView video_player;
    @BindView(R.id.video_message)
    LinearLayout video_message;
    @BindView(R.id.video_payment)
    LinearLayout video_payment;
    @BindView(R.id.video_title)
    TextView video_title;
    @BindView(R.id.video_tags)
    RecyclerView video_tags;
    @BindView(R.id.video_content)
    TextView video_content;
    @BindView(R.id.video_collect)
    CheckBox video_collect;
    @BindView(R.id.video_like)
    CheckBox video_like;
    @BindView(R.id.video_collect_num)
    TextView video_collect_num;
    @BindView(R.id.video_like_num)
    TextView video_like_num;
    @BindView(R.id.video_money)
    TextView video_money;
    @BindView(R.id.video_image)
    RelativeLayout video_image;
    @BindView(R.id.video_image_cover)
    ImageView video_image_cover;
    @BindView(R.id.video_ticket)
    Button video_ticket;

    private VideoTagAdapter myAdapter;
    private String memberId;//用户id
    private String tenantId;//租户id
    private String token;//授权token
    private String videoId;//视频id


    public void setContentView() {
        setContentView(R.layout.activity_video);
    }

    public void initView() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        video_player.setPlayerViewCallback(this);
        BarUtils.setStatusBarVisibility(this, true);
        BarUtils.setStatusBarLightMode(this, false);
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT);
        myAdapter = new VideoTagAdapter();
        RecycleUtils.chips(video_tags);
        video_tags.setAdapter(myAdapter);
    }

    public void initData() {
        ACache aCache = ACache.get(this);
        memberId = aCache.getAsString(BaseConstant.memberId);
        tenantId = aCache.getAsString(BaseConstant.tenantId);
        token = aCache.getAsString(BaseConstant.token);
        videoId = getIntent().getStringExtra(BaseConstant.videoId);
        handler.sendEmptyMessage(0);
        handler.sendEmptyMessage(1);
    }

    public void onComplete() {

    }

    @Override
    @OnClick({R.id.video_ticket, R.id.video_collect_update, R.id.video_like_update,
            R.id.video_cart, R.id.video_trolley, R.id.video_pay})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.video_ticket) {
            ToastUtils.showShort("功能尚在完善...");
        } else if (id == R.id.video_collect_update) {
            if (!video_collect.isChecked()) {
                int num = videoBean.getResult().getCollectNum() + 1;
                video_collect_num.setText(getShortNum(num) + "人收藏");
                handler.sendEmptyMessage(2);
            }
        } else if (id == R.id.video_like_update) {
            if (!video_like.isChecked()) {
                int num = videoBean.getResult().getLikeNum() + 1;
                video_like_num.setText(getShortNum(num) + "人喜欢");
                handler.sendEmptyMessage(3);
            }
        } else if (id == R.id.video_cart) {
            ActivityUtils.startActivity(UserCartActivity.class);
        } else if (id == R.id.video_trolley) {
            if (null != videoBean && null != videoBean.getResult()) {
                DBControl.insertCart(videoBean);
                ToastUtils.showShort("已添加购物车");
            }
        } else if (id == R.id.video_pay) {
            JSONObject order = getOrderCommit();
            if (null != order) {
                Bundle bundle = new Bundle();
                bundle.putString("order", order.toString());
                ActivityUtils.startActivityForResult(bundle, VideoActivity.this, OrderCommitActivity.class, 200, bundle);
            }
        }
    }

    private final Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 0://获取视频详情
                    presenter.getVideo(tenantId, token, videoId);
                    break;
                case 1://是否已收藏
                    presenter.isCollected(tenantId, token, memberId, videoId);
                    break;
                case 2://收藏
                    presenter2.collect(tenantId, token, memberId, videoId);
                    break;
                case 3://点赞
                    presenter3.like(tenantId, token, memberId, videoId);
                    break;
                case 4:
                    presenter.isBuy(tenantId, token, memberId, videoId);
                    break;
            }
            return false;
        }
    });

    private VideoBean videoBean;

    @Override
    public void onSuccess(VideoBean videoBean) {
        try {
            if (null != videoBean && null != videoBean.getResult()) {
                this.videoBean = videoBean;
                DBControl.insertHistory(videoBean);
                video_title.setText(videoBean.getResult().getTitle());
                video_content.setText(videoBean.getResult().getSummary());
                video_money.setText(String.valueOf(videoBean.getResult().getBeans()));
                video_collect_num.setText(getShortNum(videoBean.getResult().getCollectNum()) + "人收藏");
                video_like_num.setText(getShortNum(videoBean.getResult().getLikeNum()) + "人喜欢");
                if (!StringUtils.isEmpty(videoBean.getResult().getTags())) {
                    String[] strings = RegexUtils.getSplits(videoBean.getResult().getTags(), ",");
                    List<String> tags = ArrayUtils.asArrayList(strings);
                    myAdapter.setList(tags);
                    video_tags.setVisibility(View.VISIBLE);
                }
                video_message.setVisibility(View.VISIBLE);
                GlideApp.with(context).load(Retrofit.image_url + videoBean.getResult().getImageUrl()).centerCrop().into(video_image_cover);
                if (!videoBean.getResult().isFree()) {
                    LogUtils.e("不免费，请求是否购买接口");
                    handler.sendEmptyMessage(4);
                } else {
                    LogUtils.e("免费，直接播放");
                    startPlay(videoBean);
                    video_payment.setVisibility(View.GONE);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onSuccess(VideoCollectedBean videoCollectedBean) {
        video_collect.setChecked(videoCollectedBean.isResult());
    }

    @Override
    public void onSuccess(IsBuyBean isBuyBean) {
        if (isBuyBean.isResult()) {
            LogUtils.e("已购买，直接播放");
            startPlay(videoBean);
            video_payment.setVisibility(View.GONE);
        } else {
            LogUtils.e("未购买，不播放，显示购买按钮");
            video_payment.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onCollectSuccess(BaseBean baseBean) {
        video_collect.setChecked(true);
    }

    @Override
    public void onDeleteCollectSuccess(BaseBean baseBean) {

    }

    @Override
    public void onLikeSuccess(BaseBean baseBean) {
        video_like.setChecked(true);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        BarUtils.setStatusBarVisibility(this, true);
        BarUtils.setStatusBarLightMode(this, false);
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT);
    }

    @Override
    protected void onResume() {
        super.onResume();
        BarUtils.setStatusBarVisibility(this, true);
        BarUtils.setStatusBarLightMode(this, false);
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT);
        //video_data.setVisibility(View.VISIBLE);
        if (video_player.getPlayState() == SuperPlayerConst.PLAYSTATE_PLAYING) {
            video_player.onResume();
            if (video_player.getPlayMode() == SuperPlayerConst.PLAYMODE_FLOAT) {
                video_player.requestPlayMode(SuperPlayerConst.PLAYMODE_WINDOW);
            }
        }
        if (video_player.getPlayMode() == SuperPlayerConst.PLAYMODE_FULLSCREEN) {
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        BarUtils.setStatusBarVisibility(this, true);
        BarUtils.setStatusBarLightMode(this, false);
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT);
        if (video_player.getPlayMode() != SuperPlayerConst.PLAYMODE_FLOAT) {
            video_player.onPause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        video_player.release();
        if (video_player.getPlayMode() != SuperPlayerConst.PLAYMODE_FLOAT) {
            video_player.resetPlayer();
        }
    }

    @Override
    public void onStartFullScreenPlay() {
        BarUtils.setStatusBarVisibility(this, true);
        BarUtils.setStatusBarLightMode(this, false);
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT);
    }

    @Override
    public void onStopFullScreenPlay() {
        BarUtils.setStatusBarVisibility(this, true);
        BarUtils.setStatusBarLightMode(this, false);
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT);
    }

    @Override
    public void onClickFloatCloseBtn() {
        video_player.resetPlayer();
        finish();
    }

    @Override
    public void onClickSmallReturnBtn() {
        finish();
    }

    @Override
    public void onStartFloatWindowPlay() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);
    }

    private JSONObject getOrderCommit() {
        try {
            JSONObject order = new JSONObject();
            JSONArray details = new JSONArray();
            order.put("memberId", memberId);
            order.put("orderType", null);
            order.put("tradeType", "trade");
            order.put("summary", videoBean.getResult().getBeans());
            JSONObject detail = new JSONObject();
            detail.put("productId", videoBean.getResult().getId());
            detail.put("OrderQty", 1);
            detail.put("UnitPrice", 0);
            detail.put("UnitBean", videoBean.getResult().getBeans());
            detail.put("title", videoBean.getResult().getTitle());
            detail.put("content", videoBean.getResult().getSummary());
            detail.put("image", videoBean.getResult().getImageUrl());
            details.put(detail);
            order.put("details", details);
            return order;
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getShortNum(int num) {
        if (num < 999) {
            return String.valueOf(num);
        } else {
            return "999+";
        }
    }

    public void startPlay(VideoBean videoBean) {
        video_image.setVisibility(View.GONE);
        SuperPlayerModel model = new SuperPlayerModel();
        model.appId = BaseConstant.appId;//配置appId
        model.videoId = new SuperPlayerVideoId();
        model.videoId.fileId = videoBean.getResult().getVideoUrl();//配置FileId
        video_player.playWithModel(model);
    }
}